import axios from 'axios'
import { Message, Notification, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// const loading = Loading.service({
//   target: '.main-container',
//   lock: true,
//   text: 'Loading',
//   spinner: 'el-icon-loading',
//   background: 'rgba(0, 0, 0, 0.7)'
// })
function queryParse (query) {
  let res = []
  for (let k in query) {
    res.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
  }
  return res.join('&')
}
// const baseURL = process.env.NODE_ENV === 'production' ? 'https://beautisharebed.dlc-sz.com' : '/api'
// const baseURL = 'http://192.168.110.80:8110'
const baseURL = 'http://192.168.120.43:8110'

// const baseURL = 'http://180.76.157.25:8110'
// const baseURL = 'http://localhost:8110/'

const service = axios.create({
  baseURL,
  timeout: 5000
})

export const json2fd = json => {
  const fd = new FormData()
  for (let k in json) {

    fd.append(k, json[k])

  }
  return fd
}
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()
  }

  if (!(config.data instanceof FormData)) {
    config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
    config.data = queryParse(config.data)
  }
  return config
}, error => {
  console.log(error) // for debug
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
   const res = response.data;
   if (res.code === 1) {
    return res 
   } else if (res.code === 403) {
    console.log(`res.code---`,res.code);
    Notification({
      title: '警告',
      message: '您的登录凭证已过期，请重新登录,2秒后自动退出系统',
      type: 'warning'
    })
    // setTimeout(() => {
    //   store.dispatch('FedLogOut').then(() => {
    //     location.reload();// 为了重新实例化vue-router对象 避免bug
    //   }); 
    // }, 2000);
   
    } else if(res.code === 3){
      Notification({
        title: '警告',
        message: '用户未登录',
        type: 'warning'
      })
      this.$store.dispatch('FedLogOut').then(() => {
        location.reload()// In order to re-instantiate the vue-router object to avoid bugs
      })
    } else if(res.code === 21){
      Notification({
        title: '警告',
        message: '您的权限不足',
        type: 'warning'
      })
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(res)
    }
  },
  error => {
    console.log('err', error)// for debug
    Message({
      message: error.message || error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
